﻿using System.Collections.Generic;
using System.Linq;

namespace Borg.Framework
{
    public static class SlotOpenHistory
    {
        private static readonly List<SlotInfo> History = new List<SlotInfo>();

        public static List<SlotInfo> GetOpenHistory(ExtensionInfo extension)
        {
            return History.Where(si => extension == si.ExtensionInfo).ToList();
        }

        internal static void Init()
        {
            Runtime.Repository.PluginAdded += PluginAdded;
            Runtime.Repository.PluginRemoved += PluginRemoved;

            foreach (var pi in Runtime.Repository.PluginInfos)
                Register(pi);
        }

        private static void PluginAdded(object sender, PluginEventArgs args)
        {
            Register(args.PluginInfo);
        }

        private static void PluginRemoved(object sender, PluginEventArgs args)
        {
            Unregister(args.PluginInfo);
        }

        private static void RecordClosed(object sender, SlotEventArgs args)
        {
            History.Remove(args.SlotInfo);
        }

        private static void RecordOpened(object sender, SlotEventArgs args)
        {
            History.Add(args.SlotInfo);
        }

        private static void Register(PluginInfo plugin)
        {
            foreach (var sti in plugin.ExtensionTypeInfos.SelectMany(eti => eti.SlotTypeInfos))
            {
                sti.Opened += RecordOpened;
                sti.Closed += RecordClosed;
            }
        }

        private static void Unregister(PluginInfo plugin)
        {
            foreach (var sti in plugin.ExtensionTypeInfos.SelectMany(eti => eti.SlotTypeInfos))
            {
                sti.Opened -= RecordOpened;
                sti.Closed -= RecordClosed;
            }
        }

        public static IList<SlotInfo> Slots
        {
            get { return History.AsReadOnly(); }
        }
    }
}

